package com.ymsoft.myerp.api;

import com.ymsoft.myerp.common.DTO;
import com.ymsoft.myerp.common.RetEnum;
import com.ymsoft.myerp.entity.TokenCarrier;
import com.ymsoft.myerp.entity.User;
import com.ymsoft.myerp.entity.UserDetail;
import com.ymsoft.myerp.service.ILoginService;
import com.ymsoft.myerp.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @author: yzr
 * @date: 2020/4/12
 */
@RestController
@RequestMapping("/api/v1")
public class LoginApi {

    @Value("${jwt.header}")
    private String tokenHeader;

    private final ILoginService iLoginService;

    @Autowired
    public LoginApi(ILoginService iLoginService) {
        this.iLoginService = iLoginService;
    }

    @PostMapping(value = "/login")
    public DTO<TokenCarrier> login(@Valid @RequestBody User user) {
        TokenCarrier tokenCarrier = iLoginService.login(user.getUsername(), user.getPassword());
        return DTO.retSuccess(tokenCarrier);
    }

    @GetMapping(value = "/logout")
    public DTO<?> logout(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        if(StringUtils.isBlank(token)) {
            token = request.getParameter(tokenHeader);
        }
        if(StringUtils.isBlank(token)) {
            return DTO.ret(RetEnum.UNAUTHORIZED);
        }
        iLoginService.logout(token);
        return DTO.retSuccess();
    }

    @GetMapping(value = "/user")
    public DTO<?> user(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        if(StringUtils.isBlank(token)) {
            token = request.getParameter(tokenHeader);
        }
        if(StringUtils.isBlank(token)) {
            return DTO.ret(RetEnum.UNAUTHORIZED);
        }
        UserDetail userDetail = iLoginService.getUserByToken(token);
        return DTO.retSuccess(userDetail);
    }

    @GetMapping("/loginPage")
    public String login() {
        return "forward:/page/login-1.html";
    }
}
